#include "MiniBlogLayout.h"
#include "MiniBlogEntryWidget.h"
namespace Douban
{
	void MiniBlogLayout::prependWidget(MiniBlogEntryWidget* w)
	{
		i_dirtyIndex = 0;
		m_widgetList.prepend(w);
		w->show();
	}

	void MiniBlogLayout::removeWidget(MiniBlogEntryWidget* w)
	{
		int index = m_widgetList.indexOf(w);

		if(i_dirtyIndex == -1 || i_dirtyIndex > index)
			i_dirtyIndex = index;

		m_widgetList.removeAt(index);

		w->setParent(0);
		w->hide();
	}

	void MiniBlogLayout::updateLayout(MiniBlogEntryWidget* w)
	{
		int index = m_widgetList.indexOf(w);
		if(index == -1)
			return;

		if(i_dirtyIndex == -1 || i_dirtyIndex > index)
			i_dirtyIndex = index;

		updateLayout();
	}

	void MiniBlogLayout::updateLayout()
	{
		int length = m_widgetList.length();
		if(length == 0)
			return;

		int y;
		if(i_dirtyIndex == 0)
			y = -1;
		else
		{
			MiniBlogEntryWidget* w = m_widgetList.at(i_dirtyIndex-1);
			y = w->y() + w->height() + w->spacing();
		}

		for(int i=i_dirtyIndex;i<length;++i)
		{
			MiniBlogEntryWidget* w(m_widgetList.at(i));
			w->setGeometry(0,y,m_mainWidget->width(),w->heightHint());
			y = y + w->heightHint() + w->spacing();
		}

		m_mainWidget->resize(m_widgetList.at(0)->width(),y-2);
	}

	void MiniBlogLayout::widthChanged(int newWidth)
	{
		int length = m_widgetList.length();
		if(length <= 0)
			return;
		int y = -1;
		for(int i=0;i<length;++i)
		{
			MiniBlogEntryWidget* w(m_widgetList.at(i));
			w->updateContentWidth(newWidth);
			w->setGeometry(0,y,newWidth,w->heightHint());
			y = y + w->heightHint() + w->spacing();
		}
		m_mainWidget->resize(m_widgetList.at(0)->width(),y-2);
	}
}
